package com.blb.auth_service.controller;

import com.blb.auth_service.config.JwtProperties;
import com.blb.auth_service.service.IUserService;
import com.blb.common.entity.JsonResult;
import com.blb.common.entity.UserInfo;
import com.blb.common.utils.CookieUtils;
import com.blb.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录验证控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private JwtProperties properties;

    @PostMapping("/login")
    public JsonResult<UserInfo> login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        UserInfo info = userService.login(username, password);
        if(info != null){
            //验证通过，将用户加密为token
            String token = JwtUtils.generateToken(info, properties.getPrivateKey(), properties.getExpire());
            //保存token到cookie中
            CookieUtils.setCookie(request,response,properties.getCookieName(),token,
                    properties.getCookieMaxAge(),null,true);
            return new JsonResult<>(1,info);
        }
        return new JsonResult<>(0,null);
    }
}
